package com.ekuaitu.kuaitustaff.api;

import android.content.Intent;
import android.os.Build;
import android.util.Log;

import com.ekuaitu.kuaitustaff.BuildConfig;
import com.ekuaitu.kuaitustaff.activity.LoginNewActivity;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.bean.ParseResultBean;
import com.ekuaitu.kuaitustaff.bean.ResultBean;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by micha on 2016/9/21.
 */

public class ApiStore {
    private static final long DEFAULT_JSON_CACHE_SIZE = 250 * 1024 * 1204;
    private static ApiStore instance = null;
    private static Retrofit retrofit;
    private OkHttpClient.Builder builder;
    public static String objectId = null;
    private String base_url_parse;

    public ApiStore() {

    }

    public Call getApiService(final String baseUrl, final String api, final HashMap<String, String> eventMap, final ParseCallBack parseCallBack) {
        JSONObject parseJson = new JSONObject();
        try {
            parseJson.put("app_id", "3aaf0cefe92c4e8ba5cae892b798456c");
            parseJson.put("operate_user_id", MyApplication.getInstance().getUserId() + "");
            parseJson.put("operate_user_name", MyApplication.getInstance().getUserName() + "");
            parseJson.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
            parseJson.put("ip", NetUtils.getIP(MyApplication.getInstance().getApplicationContext()));
            parseJson.put("model", Build.BRAND + Build.MODEL + "");

            switch (UrlConstant.Request.BASE_URL_NEW) {
                case "https://api.mydadao.com/":
                    parseJson.put("env", "pro");
                    break;
                case "https://api-test.mydadao.com/":
                    parseJson.put("env", "test");
                    break;
                case "https://api-dev.mydadao.com/":
                    parseJson.put("env", "dev");
                    break;
                case "https://api-dev2.mydadao.com/":
                    parseJson.put("env", "dev2");
                    break;
            }
            parseJson.put("api", api);

            eventMap.put("user_id", MyApplication.getInstance().getUserId() + "");
            eventMap.put("user_name", MyApplication.getInstance().getUserName() + "");
            eventMap.put("latitude", MyApplication.getInstance().getCurPosition()[0]);
            eventMap.put("longitude", MyApplication.getInstance().getCurPosition()[1]);
            parseJson.put("event", new JSONObject(new Gson().toJson(eventMap)));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), parseJson.toString());
        Call call = getParseRetrofit().create(ApiService.class).parseEvent(body);
        call.enqueue(new Callback<ParseResultBean>() {
            @Override
            public void onResponse(Call<ParseResultBean> call, retrofit2.Response<ParseResultBean> event) {

                if (event.body() != null && event.body().getObjectId() != null) {
                    objectId = event.body().getObjectId();
                } else {
                    objectId = "";
                }
                ApiService apiService = getRetrofit(baseUrl, api, objectId).create(ApiService.class);
                parseCallBack.onSaveSuccess(apiService);

            }

            @Override
            public void onFailure(Call<ParseResultBean> call, Throwable t) {
                if (!call.isCanceled()) {
                    ApiService apiService = getRetrofit(baseUrl, api, "").create(ApiService.class);
                    parseCallBack.onSaveSuccess(apiService);
                }
            }
        });
        return call;
    }


    //框架

    public Retrofit getRetrofit(String baseUrl, String api, final String objectId) {
        this.objectId = objectId;
        if ("v/car/control".equals(api)) {
            builder = new OkHttpClient.Builder()
                    .connectTimeout(50, TimeUnit.SECONDS)
                    .readTimeout(50, TimeUnit.SECONDS)
                    .writeTimeout(50, TimeUnit.SECONDS);
        } else {
            //配置okHttp
            builder = new OkHttpClient.Builder()
                    .connectTimeout(40, TimeUnit.SECONDS)
                    .readTimeout(40, TimeUnit.SECONDS)
                    .writeTimeout(40, TimeUnit.SECONDS);
        }
        Logger.i("parse", "retrofitPre" + "   " + objectId + "     " + ((MyApplication) MyApplication.getInstance()).getHeaderToken());
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();
                Map<String, String> requestMap = (MyApplication.getInstance()).getRequestHeaderMap();
                for (String mapKey : requestMap.keySet()) {
                    if (requestMap.get(mapKey) != null) {
                        requestBuilder.header(mapKey, requestMap.get(mapKey));
                    }
                }
                return chain.proceed(requestBuilder.build());
            }
        });

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Logger.i("OkHttpClient", "OkHttpMessage:" + message);
            }
        });
        if (BuildConfig.DEBUG) {
            //debug模式
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(MyApplication.chuckInterceptor);
        } else {
            //release模式
            logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        }
        builder.addInterceptor(logging);
        builder.addInterceptor(new HttpCodeInterceptor());

        //配置Retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        return retrofit;
    }

    private Retrofit getParseRetrofit() {
        //配置okHttp
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(4, TimeUnit.SECONDS)
                .readTimeout(4, TimeUnit.SECONDS)
                .writeTimeout(4, TimeUnit.SECONDS);
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();
                requestBuilder.header("X-Parse-Application-Id", "e8b9ed3e57a3c04c56b4ec7bd82d3b47");
                requestBuilder.header("X-Parse-REST-API-Key", "4c56b4ec7bd82d3b47e8b9ed3e57a3c0");
                requestBuilder.header("Content-Type", "application/json");
                return chain.proceed(requestBuilder.build());
            }
        });

        if (BuildConfig.DEBUG) {
            //debug模式
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Logger.i("OkHttpClient", "OkHttpMessage:" + message);
                }
            });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }

        //配置Retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(UrlConstant.Request.BASE_URL_PARSE)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        return retrofit;
    }

    public Retrofit getConfigRetrofit() {
        //配置okHttp
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(4, TimeUnit.SECONDS)
                .readTimeout(4, TimeUnit.SECONDS)
                .writeTimeout(4, TimeUnit.SECONDS);
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();
                requestBuilder.header("Content-Type", "application/json");
                return chain.proceed(requestBuilder.build());
            }
        });

        if (BuildConfig.DEBUG) {
            //debug模式
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Logger.i("OkHttpClient", "OkHttpMessage:" + message);
                }
            });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }

        //配置Retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(UrlConstant.Request.BASE_URL_CONFIG)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        return retrofit;
    }

    /**
     * java bean 转化json数据  序列化
     * 解析反序列化
     *
     * @return
     */

    private Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()//允许序列化反序列化为null
                .create();
    }

    public class HttpCodeInterceptor implements Interceptor {
        public static final int HTTP_CODE_LOG_OUT = 401;//Token验证失效

        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            if (response.code() == HTTP_CODE_LOG_OUT) {
                Logger.d("退出登录", "Http退出登录");
                //ToastUtils.makeText(MyApplication.getInstance(), "请重新登录", ToastUtils.LENGTH_SHORT).show();
                Intent intent = new Intent(MyApplication.getInstance(), LoginNewActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                MyApplication.getInstance().startActivity(intent);
            }
            return response;
        }

    }

    public interface ParseCallBack {
        void onSaveSuccess(ApiService apiService);

        void onSaveFailure(String error);
    }

    public void getApiScanCodeService(final String baseUrl, final String api, final String lisencePlate, final String qrCode, final String number, final HashMap<String, String> eventMap, final ParseCallBack parseCallBack) {
        JSONObject parseJson = new JSONObject();
        try {
            parseJson.put("lisencePlate", lisencePlate);
            parseJson.put("qrCode", qrCode);
            parseJson.put("number", number);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), parseJson.toString());

        getParseRetrofit().create(ApiService.class).carBinding(body).enqueue(new Callback<ParseResultBean>() {
            @Override
            public void onResponse(Call<ParseResultBean> call, retrofit2.Response<ParseResultBean> event) {

                if (event.body() != null && event.body().getObjectId() != null) {
                    objectId = event.body().getObjectId();
                } else {
                    objectId = "";
                }
                ApiService apiService = getRetrofit(baseUrl, api, objectId).create(ApiService.class);
                parseCallBack.onSaveSuccess(apiService);
            }

            @Override
            public void onFailure(Call<ParseResultBean> call, Throwable t) {
                ApiService apiService = getRetrofit(baseUrl, api, "").create(ApiService.class);
                parseCallBack.onSaveFailure("提交失败");
            }
        });

    }

    //蓝牙操作记录
    public static void bleRecord(final String bleResult, String orderId, String carId, String command) {
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).bleRecord(MyApplication.getInstance().getRequestFieldMap(),
                orderId, carId, command, ApiStore.objectId, bleResult, "4.0", Build.MODEL)
                .enqueue(new Callback<ResultBean>() {
                    @Override
                    public void onResponse(Call<ResultBean> call, retrofit2.Response<ResultBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                        }
                    }

                    @Override
                    public void onFailure(Call<ResultBean> call, Throwable t) {
                        Log.i("neterror", "蓝牙操作记录" + t.toString());
                    }
                });
    }
}
